/**
 * <b>项目名：</b>hclv-web<br/>  
 * <b>包名：</b>com.flea.hclv.service.impl<br/>  
 * <b>文件名：</b>HHotelServiceImpl.java<br/>  
 * <b>版本信息：</b>1.0<br/>  
 * <b>日期：</b>2018年9月12日 下午3:50:38<br/>  
 * <b>COPYRIGHT 2010-2012 ALL RIGHTS RESERVED 虫子科技</b>-版权所有<br/>
 */
package com.flea.hclv.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.flea.hclv.constant.HConstant;
import com.flea.hclv.model.dao.HProductMapper;
import com.flea.hclv.model.entity.HProduct;
import com.flea.hclv.model.entity.HTripSpotsRelation;
import com.flea.hclv.model.entity.vo.ProductTripVo;
import com.flea.hclv.service.HResourceRelationService;
import com.flea.hclv.util.ServerResponse;
import com.flea.system.base.util.StringUtil;
import com.flea.system.platform.session.FleaOrgUtils;
import com.flea.system.utils.FleaStringUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.flea.hclv.model.dao.HResourceRelationMapper;
import com.flea.hclv.model.dao.HTripMapper;
import com.flea.hclv.model.entity.HResourceRelation;
import com.flea.hclv.model.entity.HTrip;
import com.flea.hclv.service.HTripService;

/**
 * @description
 * @createTime 2018年9月12日 下午3:50:38
 * @modifyTime
 * @author myflea@163.com
 * @version 1.0
 */
@Service("tripService")
public class HTripServiceImpl implements HTripService {
  private static Logger logger = LoggerFactory.getLogger(HTripServiceImpl.class);
	@Autowired
	private HTripMapper tripMapper;
	@Autowired
	private HResourceRelationMapper resourceRelationMapper;
  @Autowired
	private HProductMapper hProductMapper;
	@Autowired
  private HResourceRelationService resourceRelationService;


	@Override
	public List<HTrip> getByProductId(String productId) {


		
		List<HTrip> htps = tripMapper.selectByProductId(productId);
		
		return coverPathRelation(htps);
		
		
		
	}
	/**
	 * 
	 * @description
	 * @methodName coverPathRelation
	 * @param
	 * @returnType List<HTrip>   
	 * @throw
	 */
	private List<HTrip> coverPathRelation(List<HTrip> htps){
		List<HTrip> nhtps = new ArrayList<HTrip>();
		for (HTrip hTrip : htps) {
			List<HResourceRelation> resource = resourceRelationMapper.selectByUuid(hTrip.getId());
			hTrip.setResource(resource);
			nhtps.add(hTrip);
		}
		
		return nhtps;
	}

	@Override
	public boolean save(List<HTrip> trips) throws Exception {
		return tripMapper.insertBatch(trips) > 0;
	}

	@Override
	public boolean deleteByProductIds(List<String> productIds, String userId) throws Exception {
		int result = tripMapper.deleteByProductIds(productIds);
		return true;
		
	}

  @Override
  public ServerResponse saveTrip(String model, HttpServletRequest request) throws Exception {

	  if(StringUtil.isEmpty(model)){
	    return ServerResponse.createByErrorMessage("参数为空，异常非法");
    }
    JSONObject json = JSONObject.parseObject(model);
	  if(null==json){
	    return ServerResponse.createByErrorMessage("参数转换异常");
    }
    String productId = json.getString("productId");
    if (StringUtil.isEmpty(productId)) {
      return ServerResponse.createByErrorMessage("产品参数为空，异常");
    }
    HProduct p = hProductMapper.selectByPrimaryKey(productId);
    if(null==p){
      return ServerResponse.createByErrorMessage("产品为空，异常");
    }
    if(!HConstant.HCLV_PRODUCT_SALE_STATUS_BOOK.equals(p.getStatus())){
      return ServerResponse.createByErrorMessage("产品为非预售状态，不可进行修改");
    }


    String userId = FleaOrgUtils.getCurUserUuid(request);
    boolean resultBoolean = false;
    // 添加行程
    JSONObject jsonb = new JSONObject();
    Map<String, Object> tripAndSpotRelationMap = getTripAndSpotRelationData(jsonb, productId, userId);
    @SuppressWarnings("unchecked")
    List<HTrip> trips = (List<HTrip>) tripAndSpotRelationMap.get("trips");
    if(null!=trips&&trips.size()>0){
      resultBoolean = this.save(trips);
      if (!resultBoolean) {
        logger.error("行程添加失败，行程对象：{}", trips);
        throw new Exception("行程添加失败！");
      }
      /**
       * 行程相关图片资源
       */
      @SuppressWarnings("unchecked")
      List<HResourceRelation> relations = (List<HResourceRelation>) tripAndSpotRelationMap.get("resourceRelation");

      resultBoolean = resourceRelationService.saveImagesRelation(relations, userId);
      if (!resultBoolean) {
        logger.error("行程添加图片资源失败,行程图片：{}", relations);
        throw new Exception("行程添加图片资源失败！");
      }
    }

    return null;
  }
  /**
   * 获取行程，已经行程景点的关联关系
   *
   * @description TODO
   * @methodName getTripAndSpotRelationData
   * @param
   * @returnType Map<String , Object>
   * @throw
   */
  private Map<String, Object> getTripAndSpotRelationData(
      JSONObject jsonObject, String productId, String userId) {
    JSONObject jsonObjectTmp;
    HTrip tripTmp;
    List<HTrip> tripList = new ArrayList<>();
    List<HTripSpotsRelation> spotList = new ArrayList<>();
    List<HResourceRelation> tripPicture = new ArrayList<>();
    Map<String, Object> result = new HashMap<>();
    JSONArray tripJson = jsonObject.getJSONArray("trip");
    if(null==tripJson){
      result.put("trips", tripList);
      result.put("spots", spotList);
      result.put("resourceRelation", tripPicture);
      logger.info("行程：{}，行程图片：{}", tripList, tripPicture);
      return result;
    }
    JSONArray jsonArray = JSONObject.parseArray(tripJson.toString());

    for (Object aJsonArray : jsonArray) {
      jsonObjectTmp = (JSONObject) aJsonArray;
      ProductTripVo temTripVo = JSONObject.parseObject(
          jsonObjectTmp.toString(), ProductTripVo.class);
      // tripTmp = JSON.parseObject(jsonObjectTmp.toString(),
      // HTrip.class);
//      String tripDesc = jsonObjectTmp.getString("description");
//      JSONObject image = jsonObjectTmp.getJSONObject("resource");
//      String path = image.getString("path");
//      String resourceId = image.getString("resouceId");
      tripTmp = temTripVo.getHTrip();
      String tripTmpId = FleaStringUtils.getGenerateUUID();
      // tripTmp.setId(FleaStringUtils.getGenerateUUID());
      tripTmp.setId(tripTmpId);
//      tripTmp.setDescription(tripDesc);
      tripTmp.setProductId(productId);
      // 只有第一次创建的时候设置,修改的时候不变
      tripTmp.setCreateUser(userId);
      tripTmp.setModifyUser(userId);
      // 景点和产品关联表
      /*
       * spotList =
       * JSONArray.parseArray(jsonObjectTmp.getJSONArray("spot")
       * .toString(), HTripSpotsRelation.class); for (int j = 0; j <
       * spotList.size(); j++) {
       * spotList.get(j).setId(FleaStringUtils.getGenerateUUID());
       * spotList.get(j).setTripId(tripTmp.getId());
       * spotList.get(j).setCreateUser(userId); }
       */
      tripList.add(tripTmp);

      HResourceRelation temRelation = temTripVo.getImageRelation();
//      temRelation.setPath(path);
//      temRelation.setResouceId(resourceId);
      temRelation.setUuid(tripTmpId);
      tripPicture.add(temRelation);

    }
    result.put("trips", tripList);
    result.put("spots", spotList);
    result.put("resourceRelation", tripPicture);
    logger.info("行程：{}，行程图片：{}", tripList, tripPicture);
    return result;
  }

}
